// Sequelize ORM配置
const { Sequelize } = require('sequelize');
const config = require('../config/database');

// 创建Sequelize实例
const sequelize = new Sequelize(
  config.mysql.database,
  config.mysql.user,
  config.mysql.password,
  {
    host: config.mysql.host,
    port: config.mysql.port,
    dialect: 'mysql',
    logging: config.debug ? console.log : false,
    pool: {
      max: config.mysql.pool.max,
      min: config.mysql.pool.min,
      acquire: config.mysql.pool.acquire,
      idle: config.mysql.pool.idle
    },
    define: {
      underscored: true,
      createdAt: 'created_at',
      updatedAt: 'updated_at',
      charset: 'utf8mb4',
      collate: 'utf8mb4_unicode_ci'
    }
  }
);

// 测试连接
async function testConnection() {
  try {
    await sequelize.authenticate();
    console.log('✅ Sequelize connection has been established successfully.');
    return { success: true };
  } catch (error) {
    console.error('❌ Unable to connect to the database:', error);
    return { success: false, error: error.message };
  }
}

module.exports = {
  sequelize,
  Sequelize,
  testConnection,
  // 导出模型目录，便于后续引入所有模型
  models: {}
};